library(tidyverse)
library(plyr)
library(dplyr)
library(ggplot2)
library(zoo)
library(here)
library(readxl)
library(ggrepel)
library(scales)
library(extrafont)
library(sf)

# font_import()
# loadfonts(device = 'win')

htmltools::img(src = knitr::image_uri(file.path("logo.jpg")),
               alt = 'logo',
               style = 'position:absolute; top:0; right:0; padding:10px:')
logo
# Set a theme for this project
theme_staples <- theme_bw(base_size = 14) +
  theme(
    text=element_text(family = "Saira Condensed"),
    plot.title =element_text(family = "Archivo Narrow"),
    axis.line = element_line(color = "grey30"),
    axis.title = element_text(color = "grey30"),
    legend.background = element_rect(fill=NA, color = NA),
    legend.key = element_rect(fill=NA, color=NA),
    legend.title = element_text(color = "grey30"),
    legend.text = element_text(color = "grey30"),
    panel.background  = element_blank(),
    panel.border = element_blank(),
    plot.background = element_rect(fill=NA, colour=NA),
    panel.grid = element_line(color = "grey95")
  )

theme_set(theme_staples)

# Set project main colors
staples_colors <- c(
  `red1` = "#CC0032",
  `blue1` = "#149DCC",
  `teal1` = "#00FFB5",
  `red2` = "#FF5A4C",
  `blue2` = "#317E99"
  )

theme_colors <- c('#CC0032', '#149DCC', "#00FFB5", '#FF5A4C', "#317E99", '#C0C0C0')

# Function to extract cols as hex codes
# Adapted from https://drsimonj.svbtle.com/creating-corporate-colour-palettes-for-ggplot2
# Call cols e.g. staples_cols("red")
staples_cols <- function(...) {
  cols <- c(...)
  if (is.null(cols))
    return (staples_colors)
  staples_colors[cols]
}

# Define my palettes
staples_palettes <- list(
  `main` = staples_cols("red1", "red2", "teal1", "blue1", "blue2"),
  `cool` = staples_cols("blue2", "teal1"),
  `hot` = staples_cols("teal1", "red1"),
  `light` = staples_cols('red2', 'blue1'),
  `new` = staples_cols('white', 'teal1', 'blue2')
)

# Return function interpolating color palettes
staples_pal <- function(palette = "main", reverse = FALSE, ...) {
  pal <- staples_palettes[[palette]]
  if (reverse) pal <- rev(pal)
  colorRampPalette(pal, ...)
}

# Color scale constructor for cols
scale_color_staples <- function(palette = "main", discrete = TRUE, reverse = FALSE, ...) {
  pal <- staples_pal(palette = palette, reverse = reverse)
  if (discrete) {
    discrete_scale("colour", paste0("staples_", palette), palette = pal, ...)
  } else {
    scale_color_gradientn(colours = pal(256), ...)
  }
}

# Fill scale constructor for cols
scale_fill_staples <- function(palette = "main", discrete = TRUE, reverse = FALSE, ...) {
  pal <- staples_pal(palette = palette, reverse = reverse)
  if (discrete) {
    discrete_scale("fill", paste0("staples_", palette), palette = pal, ...)
  } else {
    scale_fill_gradientn(colours = pal(256), ...)
  }
}

Introduction

Trade wars captivate the media and broader public discourse, with flights of coverage going through the chaotic highs and lows of retaliatory and conciliatory actions. In such moments, it is often difficult to decouple the national drama from the facts of what a trade war truly is, and, perhaps more importantly, who is left paying the tab when a new trade equilibrium is reached. This project is intended to provide a short respite from the back and forth, and to go into the specifics of what a trade war means for the American people. This work presents the tangible impacts of the US-China trade war thus far, giving estimates as to what changes may be expected in the global market. Furthermore, this projects seeks to answer: what regions are likely to be hit hardest with job layoffs and rising costs? Who is the victim in a US-China trade war?

First, why China?

The national environment

Perhaps the most simple answer: the opening of the Chinese market in the 90’s. When the Chinese market first opened up in earnest to the world, it provided an opportunity for many companies looking for cheap labor to make a substantial profit, producing cheap and selling to developed nation consumers. Since then, trade between China and the World has exploded, lifting billions out of poverty in China and enabling substantial drops in the price of most consumer goods across the United States. It is important to note that this contributed substantially to making many consumer goods attainable for low-income individuals in the US: washing machines, electronics, and other household staples today all dropped significantly in price as a result of trade.

As such, demand in the United States for affordable Chinese goods has led to greater and greater levels of imports. The United States now runs the largest trade deficit in the World with China, since as a nation we buy substantially more than we sell in return. A turning point in this trend was China’s entry into the World Trade Organization in 2001, which eliminated many of the trade barriers and tariffs that previously restricted free trade. While weighting our trade balances by gross domestic product (GDP) indicates this imbalance is higher per capita in many other nations, policymakers nevertheless have expressed concern that without intervention, this imbalance will continue to widen.

# Source: https://www.census.gov/foreign-trade/balance/index.html
USall <- read_csv('country.csv')

# Parse dates for use in ggplot
USall$new_date <- as.Date(as.yearmon(USall$date))

# Redefine variable deficit to trade balance
USall$trd_bal <- -USall$deficit

# Restrict to years 1985-2017 for yearly total
USall <- USall[USall$new_date < '2018-09-01',]

# Exclude regional trade comparisons
USuni <- USall[USall$cty_code > 1000,]

# Summarize over year to adjust for seasonal spikes
USyr <- ddply(USuni, .(cty_code, year), summarize, trd_bal = sum(trd_bal))

# Prepare for ggplot
USyr$is_china <- ifelse(USyr$cty_code == 5700, 1, 0)
USyr$trd_bal <- USyr$trd_bal/1000
USyr <- USyr[USyr$year < 2018,]

###############################

ggplot(USyr, aes(x = year, y = trd_bal,
  color = as.factor(cty_code), alpha = as.factor(is_china))) +
  geom_line(size = ifelse(as.numeric(USyr$is_china) == 1, 1, 0.5)) +
  geom_vline(xintercept = 2001, linetype = 'dashed', color = staples_cols("blue1")) +
  scale_alpha_manual(values = c(.4, 1)) +
  scale_color_manual(values = c(rep('grey', 150), '#CC0032', rep('grey', 93))) +
  scale_x_continuous(breaks = seq(1985, 2017, 5), expand = c(0,0)) +
  scale_y_continuous(breaks = seq(-400, 100, 100), expand = c(0,0)) +
  annotate("text", x = 2015, y = -310, label = 'China', color = staples_cols("red1"), family = "Saira Condensed", size = 5) +
  annotate("text", x = 2000.5, y = -200, label = 'China Enters WTO', angle = 90, color = "grey30", family = "Saira Condensed", size = 5) +
  annotate("text", x = 2008.5, y = -150, label = 'Great \nRecession', angle = 0, color = "grey30", family = "Saira Condensed", size = 4) +
  annotate("rect", xmin = 2008, xmax = 2009, ymin = -400, ymax = 100, alpha = .1, fill = "grey70") +
  theme(legend.position = 'none',
        panel.grid = element_blank()) +
  annotate("text", x = 2014, y = 60, label = 'All Other Nations', family = "Saira Condensed", size = 4, color = 'grey30') +
  labs(x = 'YEAR', y = 'TRADE BALANCE (BILLIONS $USD)',
       title = 'The US-China trade gap stands out among US trade relationships',
       subtitle = 'In nominal terms, the deficit trends downward after China entered the World Trade Organization in December 2001, \nquadrupling since 2000. While population weighting reduces the deficit somewhat, it does not change this trend.', 
       caption = 'Data Source: United States Census Bureau')

The state breakdown

Breaking this trade relationship down to the state level, China runs a surplus with many of its primary US state trading partners. A balance-trade line shows most states with China as a primary foreign trade partner run a deficit, with Washington State a notable outlier running a surplus. This reliance on Chinese trade cuts across partisan lines: California and Texas, Illinois and Kentucky, Washington and South Carolina, all have something to lose in a trade war.

Many states rely substantially on trade with China as a part of their local economy. California, Illinois, Washington, Georgia, South Carolina, and Tennessee each attribute roughly five to eight percent of their state GDP to trade with China (imports and exports combined). These states are then ones with particularly more to lose from a US-China trade war, as opposed to states such as the Dakotas, Wyoming, and Montana.

# source: https://www.census.gov/foreign-trade/statistics/state/data/index.html
EXall <- read_excel('exctyall.xls',
            range = cell_rows(5:1436),
            col_types = c(rep('text', 3), rep('numeric', 9))
            )
IMall <- read_excel('imctyall.xls',
            range = cell_rows(5:1436),
            col_types = c(rep('text', 3), rep('numeric', 9))
            )

# extract only 2017 imports/exports
IMall$IMval2017 <- IMall$val2017
EXall$EXval2017 <- EXall$val2017

IMall$IMshr2017 <- IMall$share17
EXall$EXshr2017 <- EXall$share17

IMall$IMrank <- IMall$rank
EXall$EXrank <- EXall$rank

# combine by state and trading country
ImEx <- left_join(IMall, EXall, by = c('statename', 'countryd'))

# subset only chinese imports and exports
ImExCN <- subset(ImEx, (ImEx$countryd %in% 'China'))

# specify if china is top trading partner
ImExCN$trd_main <- ifelse(ImExCN$IMrank %in% c(1:3) & ImExCN$EXrank %in% c(1:3), 'Yes', 'No')

# convert millions to billions for each of graph reading
ImExCN$IMval2017 <- ImExCN$IMval2017/1000
ImExCN$EXval2017 <- ImExCN$EXval2017/1000

ImExCN$IMshr2017 <- ImExCN$IMshr2017/100
ImExCN$EXshr2017 <- ImExCN$EXshr2017/100

# Create relative measure of (imports+exports)/gdp per state
# Source: https://apps.bea.gov/regional/histdata/releases/0718gdpstate/index.cfm
gdp <- read_csv('SQGDP2.csv')
gdp <- subset(gdp, gdp$IndustryId == 1)
colnames(gdp)[2] <- "statename"
ImExCN <- left_join(ImExCN, gdp, by = 'statename')
ImExCN <- subset(ImExCN, !is.na(ImExCN$Unit))
ImExCN <- subset(ImExCN, ImExCN$statename != 'District of Columbia')
ImExCN$share_gdp <- 100*(ImExCN$IMval2017 + ImExCN$EXval2017)/(as.numeric(ImExCN$`2017:Q4`)/1000)

###############################

ImExCN[order(-ImExCN$share_gdp),] %>%
ggplot(aes(x = IMval2017, y = EXval2017,
  fill = as.factor(trd_main), size = share_gdp)) +
  geom_jitter(pch=21) +
  geom_abline(intercept = 0, slope = 1, linetype = 'dashed', color = staples_cols('blue1')) +
  guides(size=guide_legend(title="% 2017 State GDP")) +
  guides(fill=guide_legend(title="China top partner?")) +
  coord_trans(x="log2") +
  ylim(0,20) +
  theme(legend.position = c(.15, .60)) +
  scale_fill_manual(values = c('grey', '#CC0032')) +
  geom_text_repel(aes(label=ifelse(share_gdp > 3,as.character(statename),'')),hjust=.5, vjust=-2, size = 3, color = "grey30") +
  annotate("text", x = 9, y = 12.4, angle = 60, label = "Balanced-Trade Line", color = "grey30", size = 5, family = "Saira Condensed") +
  scale_radius(range = c(1,12)) +
  annotate("text", x = 80, y = 13, label = 'California and Texas are\ntwo heavy importers with\nlarge consumer populations', family = "Saira Condensed", color = 'grey30') +
  labs(x = 'LOG IMPORTS (BILLIONS $USD)', y = 'EXPORTS (BILLIONS $USD)',
       title = 'The states rely heavily on Chinese market access for imports and exports',
       subtitle = 'In 2017, a plurality of states counted China a primary trade partner, with imports and exports representing four to \neight percent of state gross domestic product (GDP). The balanced-trade line indicates very few states run a surplus.', 
       caption = 'Data Source: United States Census Bureau & Bureau of Economic Analysis')

Trade wars: the theory

For these trade-reliant states, what impacts might we expect from trade tariffs? Microeconomic theory can be of some help to us here, describing the fundamental mechanisms operating during a trade war.

Domestic businesses are usually price-takers from a global market, which with China’s help has made many goods cheap (dotted line). As a result, more consumers have been able to buy cheaper goods, maximizing the surplus consumers maintain. Meanwhile, local businessese are forced to sell at a lower price, minimizing the profit they go home with and potentially stifling industry growth.

When a tariff is introduced, prices go up and quantity goes down, hurting the consumer by increasing costs, and threfore reducing the number of people who may buy certian goods. Meanwhile, domestic suppliers can become more competitive, and can begin to reap the benefits of higher consumer costs. This could mean growing their businesses in the US or abroad.

However, importantly we lose some potential surplus in dead weight losses, which ends up hurting our consumers, producers, and the government in the long run. Without sufficient gains, tariffs then shrink the pie to be gained by society, working only to redirect that wealth to businesses rather than consumers.

# credit to Andrew Heiss for creating this package: https://github.com/andrewheiss/reconPlots
library(devtools)
library(reconPlots)

line1 <- data.frame(Hmisc::bezier(c(10, 80, 90), c(5, 30, 45)))
line2 <- data.frame(Hmisc::bezier(c(10, 30, 90), c(45, 20, 5)))
line3 <- data.frame(Hmisc::bezier(c(0, 100), c(8, 8)))
line4 <- data.frame(Hmisc::bezier(c(0, 100), c(15, 15)))

line_intersect <- as.data.frame(curve_intersect(line1, line2))
base_intersect1 <- as.data.frame(curve_intersect(line1, line3))
base_intersect2 <- as.data.frame(curve_intersect(line2, line3))
new_intersect1 <- as.data.frame(curve_intersect(line1, line4))
new_intersect2 <- as.data.frame(curve_intersect(line2, line4))

###############################
ggplot(mapping = aes(x = x, y = y)) +
  geom_path(data = line1, color = staples_cols("red1"), size = 1) +
  geom_path(data = line2, color = staples_cols("blue2"), size = 1) +
  geom_path(data = line3, color = "black", linetype = 'dashed', size = 1) +
  geom_path(data = line4, color = "black", size = 1) +
  geom_point(data = base_intersect1, size = 2, color = 'grey40') +
  geom_point(data = base_intersect2, size = 2, color = 'grey40') +
  geom_point(data = new_intersect1, size = 2, color = 'black') +
  geom_point(data = new_intersect2, size = 2, color = 'black') +
  geom_ribbon(data = subset(line2, line2$x <= 57.33401),
      aes(ymin = 15, ymax = y), fill = staples_cols("blue1"), alpha = .2) +
  geom_ribbon(data = subset(line1, line1$x <= 36.60526),
      aes(ymin = y, ymax = 15), fill = staples_cols("red2"), alpha = .2) +
  geom_segment(data = new_intersect1,
      aes(x = x, y = 0, xend = x, yend = y), lty = "dotted") +
  geom_segment(data = new_intersect2,
      aes(x = x, y = 0, xend = x, yend = y), lty = "dotted") +
  coord_equal() +
  annotate("text", x = 88, y = 17, label = 'World Price + Tariffs', family = "Saira Condensed", size = 6, color = 'black') +
  annotate("text", x = 70, y = 33, angle = 30, label = 'Domestic Supply', family = "Saira Condensed", size = 6, color = staples_cols("red1")) +
  annotate("text", x = 30, y = 31, angle = -31, label = 'Demand', family = "Saira Condensed", size = 6, color = staples_cols("blue2")) +
  annotate("text", x = 47, y = 11.5, label = 'Lost Consumer Surplus', family = "Saira Condensed", color = 'black', size = 4) +
  annotate("text", x = 92, y = 10, label = 'World Price', family = "Saira Condensed", size = 6, color = 'black') +
  annotate("text", x = 21, y = 22.5, label = 'New Consumer Surplus', family = "Saira Condensed", color = staples_cols("blue2"), size = 4) +
  annotate("text", x = 18, y = 12, label = 'Producer Surplus', family = "Saira Condensed", color = staples_cols("red1"), size = 4) +
  annotate("text", x = 65, y = 19, label = 'Under tariffs, costs go up \nand access to goods falls', family = "Saira Condensed", color = 'grey30') +
  annotate("segment", x = 70, xend = 59, y = 9, yend = 13, colour = "grey30", arrow=arrow(length = unit(0.02, "npc"))) +
  annotate("segment", x = 25, xend = 35, y = 9, yend = 13, colour = "grey30", arrow=arrow(length = unit(0.02, "npc"))) +
  annotate("text", x = 72, y = 3, label = 'With trade, we get lower \nprices and higher supply \nfor domestic consumers', family = "Saira Condensed", color = 'grey30') +
  annotate("text", x = 25, y = 3, label = 'Tariffs let domestic \n businesses charge more \n and make more profit', family = "Saira Condensed", color = 'grey30') +
  labs(x = 'QUANTITY', y = 'PRICE',
       title = 'Theory suggests tariffs hurt consumers but may help domestic suppliers',
       subtitle = 'With a given imported good, consumers benefit from lower costs and high quantities. When tariffs push up outside \nprices, quantity goes down and prices go up, hurting consumers and giving relatively little to domestic businesses.')

The consumer-side question

The goods hit the hardest

General equilibrium theory suggests that prices for consumer goods will go up. However, the exact goods impacted by a trade war depend on both the relative proportion of Chinese goods making up American consumption in each category, as well as the specific tariff policy of the U.S. administration.

The vast majority of Chinese imports to the U.S. are in consumer electronics and appliances, trade in which totalled over $150 billion in 2017. This includes nearly all small electronics and household appliances, as well as the parts imported to produce motor vehicles by U.S. manufacturers.

The three rounds of 25 percent tariffs set by the Trump administration impact many of the largest import groups, including applances, motor vehicles, and furniture. Many of the categories subject to no current tariff in the figure below have been threatened, which might also play a role in speculative price increases by corporations. As of late February, the Trump Administration has threatened a market-wide tariff on Chinese goods, which would impact all of the remaining categories (including smaller areas not shown).

# source: https://comtrade.un.org/data/
com <- read_csv('comtrade.csv')

# Remove re-import/export data
com <- subset(com, com$`Trade Flow Code` < 3 & com$`Commodity Code` < 98)

# turn to billions USD
com_fam <- ddply(com, .(`Trade Flow`, `Commodity Code`), summarize, `Trade Value` = sum(`Trade Value (US$)`))
com_fam$`Trade Value` <- as.numeric(com_fam$`Trade Value`)
com_fam$`Trade Value` <- com_fam$`Trade Value`/1000000000

# filter to only top 25 of exports/imports
com_fam_ex <- subset(com_fam, com_fam$`Trade Flow` == 'Export')
com_fam_im <- subset(com_fam, com_fam$`Trade Flow` == 'Import')

com_fam_ex <- com_fam_ex[order(com_fam_ex$`Trade Value`),]
com_fam_im <- com_fam_im[order(com_fam_im$`Trade Value`),]

com_fam_ex$`Commodity Code` <- factor(com_fam_ex$`Commodity Code`,
                          levels = com_fam_ex$`Commodity Code`[
                          order(com_fam_ex$`Trade Value`)])
com_fam_ex <- com_fam_ex[72:96,]

com_fam_im$`Commodity Code` <- factor(com_fam_im$`Commodity Code`,
                          levels = com_fam_im$`Commodity Code`[
                          order(com_fam_im$`Trade Value`)])
com_fam_im <- com_fam_im[72:96,]

# rename, since categories are just horrible
com_fam_ex$Commodity <- ifelse(com_fam_ex$`Commodity Code` == 88, 'Aircraft & Spacecraft',
                        ifelse(com_fam_ex$`Commodity Code` == 84, 'Mechanical Machinery',
                        ifelse(com_fam_ex$`Commodity Code` == 12, 'Oils, Grains, & Straw',
                        ifelse(com_fam_ex$`Commodity Code` == 87, 'Cars, Vehicles, & Parts',
                        ifelse(com_fam_ex$`Commodity Code` == 85, 'Electronics & Equipment',
                        ifelse(com_fam_ex$`Commodity Code` == 90, 'Medical/Scientific Instruments',
                        ifelse(com_fam_ex$`Commodity Code` == 27, 'Mineral Fuels & Products',
                        ifelse(com_fam_ex$`Commodity Code` == 39, 'Plastic Goods',
                        ifelse(com_fam_ex$`Commodity Code` == 47, 'Recycled Wood Pulp & Paper',
                        ifelse(com_fam_ex$`Commodity Code` == 44, 'Wood & Charcoal',
                        ifelse(com_fam_ex$`Commodity Code` == 29, 'Organic Chemicals',
                        ifelse(com_fam_ex$`Commodity Code` == 30, 'Pharmaceuticals',
                        ifelse(com_fam_ex$`Commodity Code` == 38, 'Chemical Products',
                        ifelse(com_fam_ex$`Commodity Code` == 74, 'Copper',
                        ifelse(com_fam_ex$`Commodity Code` == 76, 'Aluminum',
                        ifelse(com_fam_ex$`Commodity Code` == 10, 'Grains & Cereals',
                        ifelse(com_fam_ex$`Commodity Code` == 3, 'Fish & Other Seafoods',
                        ifelse(com_fam_ex$`Commodity Code` == 71, 'Precious Stones & Metals',
                        ifelse(com_fam_ex$`Commodity Code` == 41, 'Hides & Leather',
                        ifelse(com_fam_ex$`Commodity Code` == 26, 'Ores & Ash',
                        ifelse(com_fam_ex$`Commodity Code` == 72, 'Iron & Steel, Raw',
                        ifelse(com_fam_ex$`Commodity Code` == 52, 'Cotton',
                        ifelse(com_fam_ex$`Commodity Code` == 28, 'Inorgnic Compounds & Rare Metals',
                        ifelse(com_fam_ex$`Commodity Code` == 48, 'Paper & Paperboard',
                        ifelse(com_fam_ex$`Commodity Code` == 73, 'Iron or Steel Goods',
                        NA)))))))))))))))))))))))))

com_fam_im$Commodity <- ifelse(com_fam_im$`Commodity Code` == 94, 'Furniture, Bedding, & Lights',
                        ifelse(com_fam_im$`Commodity Code` == 84, 'Mechanical Machinery',
                        ifelse(com_fam_im$`Commodity Code` == 95, 'Toys & Sports Equipment',
                        ifelse(com_fam_im$`Commodity Code` == 87, 'Cars, Vehicles, & Parts',
                        ifelse(com_fam_im$`Commodity Code` == 85, 'Electronics & Equipment',
                        ifelse(com_fam_im$`Commodity Code` == 90, 'Medical/Scientific Instruments',
                        ifelse(com_fam_im$`Commodity Code` == 61, 'Knitted Clothing/Apparel',
                        ifelse(com_fam_im$`Commodity Code` == 39, 'Plastic Goods',
                        ifelse(com_fam_im$`Commodity Code` == 64, 'Footwear',
                        ifelse(com_fam_im$`Commodity Code` == 44, 'Wood & Charcoal',
                        ifelse(com_fam_im$`Commodity Code` == 29, 'Organic Chemicals',
                        ifelse(com_fam_im$`Commodity Code` == 62, 'Non-Knitted Clothing/Apparel',
                        ifelse(com_fam_im$`Commodity Code` == 63, 'Textiles & Worn Clothing',
                        ifelse(com_fam_im$`Commodity Code` == 42, 'Leather Goods',
                        ifelse(com_fam_im$`Commodity Code` == 76, 'Aluminum',
                        ifelse(com_fam_im$`Commodity Code` == 83, 'Base Metal Products',
                        ifelse(com_fam_im$`Commodity Code` == 82, 'Tools & Cutlery',
                        ifelse(com_fam_im$`Commodity Code` == 71, 'Precious Stones & Metals',
                        ifelse(com_fam_im$`Commodity Code` == 40, 'Rubber Products',
                        ifelse(com_fam_im$`Commodity Code` == 96, 'Other Manufactured Goods',
                        ifelse(com_fam_im$`Commodity Code` == 70, 'Glass & Glassware',
                        ifelse(com_fam_im$`Commodity Code` == 69, 'Ceramic Products',
                        ifelse(com_fam_im$`Commodity Code` == 49, 'Printed Books & Other Print',
                        ifelse(com_fam_im$`Commodity Code` == 48, 'Paper & Paperboard',
                        ifelse(com_fam_im$`Commodity Code` == 73, 'Iron or Steel Goods',
                        NA))))))))))))))))))))))))) 

com_fam_ex$`Commodity` <- factor(com_fam_ex$`Commodity`,
                                 levels = com_fam_ex$`Commodity`[
                                   order(com_fam_ex$`Trade Value`)])
com_fam_ex <- com_fam_ex[10:25,]
com_fam_ex$tariff <- ifelse(com_fam_ex$`Commodity Code` %in% c(3, 10, 12, 52, 87, 28, 29, 30, 38), 'Tariff in Place',
                                   'No Tariff Set')

com_fam_im$`Commodity` <- factor(com_fam_im$`Commodity`,
                                 levels = com_fam_im$`Commodity`[
                                   order(com_fam_im$`Trade Value`)])
com_fam_im <- com_fam_im[10:25,]
com_fam_im$tariff <- ifelse(com_fam_im$`Commodity Code` %in% c(44, 83, 42, 29, 94), 'Round 3 (Sept 2018)',
                     ifelse(com_fam_im$`Commodity Code` %in% c(73, 39), 'Round 2 (Aug 2018)', 
                     ifelse(com_fam_im$`Commodity Code` %in% c(90, 87, 84, 85), 'Round 1 (Jul 2018)', 
                     'No Tariff Yet Set')))

###############################
ggplot(com_fam_im, aes(`Commodity`, `Trade Value`)) +
  geom_col(aes(fill = tariff), color = 'black', width = 0.8) +
  coord_flip() +
  theme(panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(),
        legend.position = c(.7, .40)) +
  scale_y_continuous(labels = comma, breaks = seq(0, 150, 50), expand = c(0,0)) +
  scale_fill_manual("Tariffs Set by US", values = c('light grey', '#317E99', '#149DCC', '#00FFB5')) +
  annotate("text", x = 9.1, y = 30, label = 'Clothing and toys\nhave not yet\nbeen targeted', family = "Saira Condensed", color = 'grey30') +
  annotate("text", x = 14, y = 133, label = 'Electronics and\nappliances are hardest\nhit by current tariffs', family = "Saira Condensed", color = 'grey30') +
  labs(x = '', y = 'TRADE IMPORTS (BILLIONS $USD)',
       title = 'Most US imports from China are consumer electronics targeted by current tariffs',
       subtitle = 'As of 2017, most Chinese imports were modern consumer staples, including electronics and house \nappliances. The Trump administration has imposed 25 percent tariffs on most of these goods.', 
       caption = 'Data Source: UN Comtrade International Trade Statistics & Personally Compiled Tariffs Listings')

Prices are rising in response

Preliminary trade data show that these price increases have already begun, despite temporary holds on full tariff enactments until March 2018. The red hues on the horizon chart below signify percentage price increases on a monthly basis, whereas blue hues signify prices falling for each respective good. An example is given for all appliances, with the colored protions of the graph being collapsed into one succint chart:

# Data source: https://beta.bls.gov/dataViewer/view/8de38039b69045d6ab7fe131c44312cb
# Bureau of Labor Statistics Consumer Price Index Series
bls <- read_csv('bls_cpi.csv')
bls$new_date <- as.Date(as.yearmon(bls$date))

# Create prct diff from base date (Jan 2016) to control for initial difference in CPI
bls$prct_base <- (bls$cpi/bls$base - 1)*100

# Create rolling prct change from last 3 months
bls$prct_chng <- (bls$cpi/lag(bls$cpi, n=3) - 1)*100
bls$prct_chng <- ifelse(bls$date == 'Jan 2016' | bls$date == 'Feb 2016' | bls$date == 'Mar 2016', NA, bls$prct_chng)

# rename, since categories are just horrible
bls$id <- ifelse(bls$id == 'CUSR0000SA311', 'Clothing & Apparel',
          ifelse(bls$id == 'CUSR0000SAD', 'All Durable Goods',
          ifelse(bls$id == 'CUSR0000SAH3', 'Furniture & Bedding',
          ifelse(bls$id == 'CUSR0000SEAE', 'All Footwear',
          ifelse(bls$id == 'CUSR0000SEHK', 'Appliances',
          ifelse(bls$id == 'CUSR0000SEHM', 'Tools & Hardware',
          ifelse(bls$id == 'CUSR0000SERC', 'Sporting Goods',
          ifelse(bls$id == 'CUSR0000SERE01', 'Toys',
          ifelse(bls$id == 'CUSR0000SETA', 'Motor Vehicles',
          ifelse(bls$id == 'CUSR0000SETC', 'Vehicle Parts & Equipment',
            bls$id))))))))))

# Set the bands for horizon plot
max.y <- max(abs(bls$prct_chng), na.rm=T)
nbands = 3
hrzn_scale <- max(max.y/nbands)
h1 <- hrzn_scale
h2 <- hrzn_scale*2

bls$ypos1 <- ifelse(bls$prct_chng > 0, pmin(bls$prct_chng, h1), 0)
bls$ypos2 <- ifelse(bls$prct_chng > h1, pmin(bls$prct_chng-h1, h1), 0)
bls$ypos3 <- ifelse(bls$prct_chng > h2, pmin(bls$prct_chng-h2, h1), 0)
bls$yneg1 <- ifelse(bls$prct_chng < 0, pmin(-bls$prct_chng, h1), 0)
bls$yneg2 <- ifelse(bls$prct_chng < -h1, pmin(-bls$prct_chng-h1, h1), 0)
bls$yneg3 <- ifelse(bls$prct_chng < -h2, pmin(-bls$prct_chng-h2, h1), 0)

# Divide into explanatory graph and full graph
bls <- subset(bls, !is.na(bls$prct_chng))
bls_dur <- subset(bls, bls$id == "Appliances")
bls_all <- subset(bls, bls$id != "All Durable Goods")

###############################
# Create sample graph
ggplot(bls_dur, aes(x = new_date)) +
  geom_line(aes(y = prct_chng)) +
  geom_ribbon(aes(ymin = 0, ymax = ypos1), fill='#fecc5c', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = ypos2), fill='#FF5A4C', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = ypos3), fill='#CC0032', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = -yneg1), fill='#00FFB5', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = -yneg2), fill='#149DCC', alpha=0.25) +
  geom_vline(xintercept = as.Date('2018-01-01'), size = 1) +
  scale_y_continuous(breaks=c(-1.5,0,1.5,3)) +
  scale_x_date(date_breaks = "3 months" , expand = c(0,0), date_labels = "%b%Y") +
  theme(strip.text.y = element_text(angle = 0)) +
  annotate("text", x = as.Date('2017-12-15'), y = 1.75, label = 'Trade War Starts', angle = 90, color = 'grey30', family = "Saira Condensed", size = 5) +
  annotate("text", x = as.Date('2017-05-10'), y = -1.5, label = 'Prices are consistently falling \nleading into 2018, following a long trend', family = "Saira Condensed", color = 'grey30') +
    annotate("text", x = as.Date('2018-09-01'), y = 2.65, label = 'Prices jump as \nthe trade war begins', family = "Saira Condensed", color = 'grey30') +
  labs(x = 'YEAR', y = 'ROLLING % PRICE CHANGE (3 MONTHS)',
       title = 'Rolling percent change in appliance prices can be simplified through color bands',
       subtitle = 'For positive and negative changes, darker overlapped hues signify greater values in a simplified form. Then, \nall color bands are fit into one single band space, succintly describing changes for several different goods.', 
       caption = 'Data Sources: Bureau of Labor Statistics Consumer Price Index Series')

As the horizon chart for toys shows, non-tariffed goods continue to follow a downward trend in price since before 2016. In stark comparison are now-tariffed goods, which show sharp price increases beginning in 2018, in-line with the speculation and enactment of the tariffs in question.

Most notable is the trend for appliances, whih all in all have increased in price by six percent since December 2017. Even in cases where prices have not increased, any downward historic price trend has stagnated, and the prices of goods have leveled off. Multiple goods have returned to early 2017 levels already, meaning consumers are going home with less money in their pockets. These trends will only be worsened if the full tariff regime is instituted March 2019.

###############################
# Create graph of all goods in top 9 categories of imports
ggplot(bls, aes(x = new_date)) +
  geom_ribbon(aes(ymin = 0, ymax = ypos1), fill='#FECC5C', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = ypos2), fill='#FF5A4C', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = ypos3), fill='#CC0032', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = yneg1), fill='#00FFB5', alpha=0.25) +
  geom_ribbon(aes(ymin = 0, ymax = yneg2), fill='#149DCC', alpha=0.25) +
  geom_vline(xintercept = as.Date('2018-01-01'), size = 1) +
  facet_grid(id ~ .) +
  theme(strip.text.y = element_text(angle = 0, hjust = 0, color = 'grey30'),
        strip.background = element_blank()) +
  scale_y_continuous(labels = NULL, breaks=c(0,1.5,.75)) +
  scale_x_date(date_breaks = "3 months" , expand = c(0,0), date_labels = "%b%Y") +
  labs(x = 'YEAR', y = 'ROLLING % PRICE CHANGE (3 MONTHS)',
       title = 'Rolling percent change in consumer prices show tariffs already impacting goods',
       subtitle = 'As of December 2018, many tariffed imports ticked up in price (red hues), particularly appliances. This includes \neverything from washing machines to iphones. Prior to the trade war, goods prices were generally falling (blue hue).', 
       caption = 'Data Sources: Bureau of Labor Statistics Consumer Price Index Series')

The grim producer view

US exports under tariff

US consumers aren’t the only ones experiencing preliminarily negative consequences from the trade war. Producers in the United States now pay higher costs for raw materials, particuarly steel, some of which they are unable or unwilling to pass on to consumers. But in addition to this, Chinese tariffs on their exports are likely to take their toll.

China is still the largest importer of US goods, and as a result of the trade war several large categories of exports have had 25 percent tariffs levied against them. Those goods most impacted come from rural and old industrial communities, often the most sensitive to price shifts when it comes to laying off workers and outsourcing labor.

###############################
# Plot comparative trade in commodity groups nationally
ggplot(com_fam_ex, aes(`Commodity`, `Trade Value`)) +
  geom_col(aes(fill = tariff), color = 'black', width = 0.8) +
  coord_flip() +
  theme(panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(),
        legend.position = c(.7, .40)) +
  scale_y_continuous(labels = comma, breaks = seq(0, 15, 5), expand = c(0,0)) +
  scale_fill_manual("Tariffs Set by China", values = c('light grey', '#CC0032')) +
  annotate("text", x = 13.5, y = 14.75, label = 'Farmers and hubs\nof American industry\nare specifically targeted', family = "Saira Condensed", color = 'grey30') +
  labs(x = '', y = 'TRADE EXPORTS (BILLIONS $USD)',
       title = 'US exports to China come from the rust belt and rural industries',
       subtitle = 'As of 2017, US exports to China mostly consist of vehicles and agricultural products - both primarily \nfrom rural and midwest industrial hubs. These regions have been targeted by Chinese tariffs.', 
       caption = 'Data Source: UN Comtrade International Trade Statistics Database')

A by-county breakdown

An analysis of exports by county finds that industry relying on Chinese markets are much more dispersed than one might first believe. While there exist hubs in Washington state, California, and New York, there are also large export areas in Texas, Georgia, Tennessee, and the Rust Belt states. This suggests tariffs levied will impact producers in several states adversly, even as they benefit from higher consumer prices.

library(maps)
library(mapdata)
library(rgdal)
library(rgeos)
library(zipcode)
library(albersusa)

# Extract zipcode specific data
data(zipcode)
zipcode$ZIP3 <- substr(zipcode$zip, 1, 3)
zipcode$ZIP3 <- as.numeric(zipcode$ZIP3)

# Source: http://tse.export.gov/metro/SelectReports.aspx?DATA=Metro
# International Trade Administration, Department of Commerce
exp <- read_csv('2017_exports_zip.csv')
exp$ZIP3 <- as.numeric(exp$ZIP3)
exp$`Full Year` <- ifelse(exp$`Full Year` == 'D', 0, exp$`Full Year`)

zip <- merge(zipcode, exp, by = 'ZIP3')
zip$`Full Year` <- as.numeric(zip$`Full Year`)
zip$zip <- as.numeric(zip$zip)

div.zip <- zip
div.zip$cnt <- 1
div.zip <- ddply(div.zip, .(ZIP3), summarize, div = sum(cnt))

# Join zip3-specific data to each zip, creating div variable
zip <- left_join(zip, div.zip, by = 'ZIP3')

# Source: http://mcdc.missouri.edu/applications/geocorr2014.html
# Missouri Census Data Center
geo <- read_csv('geocorr2014.csv')
geo$zip <- as.numeric(as.character(geo$zcta5))

# Collect population data to weight zip breakdown by
df.zip <- merge(zip, geo, by = 'zip')
df.zip$pop10 <- as.numeric(df.zip$pop10)
df.zip$afact <- as.numeric(df.zip$afact)
df.zip$`Full Year` <- as.numeric(df.zip$`Full Year`)
df.zip <- ddply(df.zip, .(county), summarize, pop = sum(pop10*afact), exports = sum(`Full Year`*afact/div))

cty_sf <- counties_sf("aeqd")
cty_sf$county <- cty_sf$fips

# Join and accumulate by county level
data.zip <- left_join(cty_sf, df.zip, by = "county")

data.zip$exp_pop <- data.zip$exports/data.zip$pop

data.zip$bins <- cut(data.zip$exp_pop, c(0,1500, 3000, 4500, 6000, 1000000), include.lowest = T, labels = c("0-1,500", "1,500-3,000", "3,000-4,500", "4,500-6,000", "6,000+"))

###############################
filter(data.zip, !is.na(bins)) %>% 
ggplot(aes(fill = bins, color = bins)) +
  geom_sf(alpha=0.8) +
  scale_fill_staples(discrete = T, palette = 'main') +
  scale_color_staples(discrete = T, palette = 'main') +
  theme(
    axis.ticks = element_line(color = NA),
    axis.line = element_line(color = NA),
    axis.text = element_text(color = NA),
    legend.title = element_text(face = 'bold', size = 12)) +
  guides(fill=guide_legend(title="Exports per Capita ($USD)"),
         color=guide_legend(title="Exports per Capita ($USD)")) +
  labs(title = 'U.S. exports per capita are highest in the Midwest and Texas',
       subtitle = 'As of 2017, every county traded with China, with industrial hubs in Washington state, Texas, and the Rust Belt having \nhight export-per-person ratios. But this isnt unique to cities - the rural Midwest also depends on the free flow of trade.',
       caption = 'Data Sources: International Trade Administration & Missouri Census Data Center')

The rural reliance

Rurality and exports

It is also important to note that, contrary to the popular narrative, rural populations are just as susceptible to interruptions of free trade with our major trade partners. Many of the counties with the highest exports per capita are in rural parts of each state.

An analysis of state imports and exports per capita compared to the percent of the state population in rural areas finds more rural areas may actually rely more heavily on export access to countries like China to market their goods. Meanwhile, urban-centric states will likely suffer more from the increased commodity prices already cropping up for tariffed goods.

# Source: https://www.census.gov/foreign-trade/statistics/state/origin_movement/index.html#2017; https://www.census.gov/geo/reference/ua/urban-rural-2010.html
rururb <- read_csv('rur_urban2010.csv')

rururb$val_pop <- rururb$value*1000000/(rururb$POP_URBAN+rururb$POP_RURAL)
rururb$bins <- cut(rururb$POPPCT_RURAL, breaks = c(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65),
                   include.lowest = T,
                   labels = c("0-5", "5-10", "10-15", "15-20", "20-25", "25-30", "30-35", "35-40",
                              "40-45", "45-50", "50-55", "55-60", "60+"))

rururb$val_pop <- ifelse(rururb$type == "Imports", -1*rururb$val_pop, rururb$val_pop)
mids <- ddply(rururb, .(type, bins), summarize, val_mean = mean(val_pop))

rururb <- left_join(rururb, mids, by = c('bins', 'type'))
rururb$dist <- (1 - abs((rururb$val_mean - rururb$val_pop)/rururb$val_mean))

###############################
ggplot(rururb, aes(x = bins, y = val_pop, fill = type, color = type, alpha = dist)) +
  geom_point(data = subset(rururb, type = 'Imports'), stat = 'identity', size = 3) +
  geom_point(data = subset(rururb, type = 'Exports'), stat = "identity", size = 3) +
  geom_hline(yintercept = 0) +
  scale_fill_staples(discrete = T, palette = 'main') +
  scale_color_staples(discrete = T, palette = 'main') +
  guides(fill=guide_legend(title="Trade Flow"), color=guide_legend(title="Trade Flow")) +
  coord_flip() +
  scale_alpha(guide = 'none') +
  annotate("text", x = 2.5, y = 11000, label = 'Two outliers from this\ngeneral trend are Texas\nand Washington State', family = "Saira Condensed", color = 'grey30') +
  labs(x="% RURAL POPULATION", y = "VALUE PER CAPITA ($USD)",
       title = 'Rural states have just as much (or even more) to lose from export tariffs',
       subtitle = '2010 rural population data suggest a positive relationship between rural population share and export value per \ncapita. Meanwhile, large urban states consume more imports per capita, making them sensitive to import tariffs.',
       caption = 'Data Sources: International Trade Administration & U.S. Census Bureau')

US farmers are suffering

The rural reliance on export markets has made the agricultural industry an area of intense focus for both US policy and Chinese tariffs. China severly limited its purchase of US farm gods in 2018, prompting the Trump Administration to invoke farmer subsidies to partially offset their losses. However, it is likely that these hardships will continue for American farming communities.

To identify the most impacted locales, the next cartogram weights each states’ size by the number of farms per capita. This analysis finds acute populations of farmers across the Midwest, but also in more eastern regions, as well as a hotspot in the state of Texas. These populations were among the first to be impacted by Chinese tariffs on soybeans and other foodstuffs, and they likely will remain the hardest hit as the trade war continues.

library(cartogram)
library(tmap)
library(rgdal)
library(tidycensus)

# Source: https://www.icip.iastate.edu/tables/agriculture/farms-by-state
farms <- read_csv('us_farms.csv')
farms$farms <- ifelse(is.na(farms$farms), 0, farms$farms)
farms$state <- farms$statename
farms$Farms <- farms$farms/farms$county_count

census_api_key("b604f782915a3324852654db67fca9ce5e97538f")
state_sf <- get_acs("state", variables = "B01001_001", geometry = T, shift_geo = T)
state_sf$state <- state_sf$NAME

data.state <- left_join(state_sf, farms, by = "state")
data.state$Farms <- data.state$farms/data.state$estimate*10000

state.cont <- cartogram_cont(data.state, "Farms", itermax = 5)

state.cont$bins <- cut(state.cont$Farms, c(0, 50, 100, 200, 300, 500), include.lowest = T, labels = c("0-50", "50-100", "100-200", "200-300", "300+"))

###############################
ggplot(data = state.cont, aes(fill = bins)) +
  geom_sf(alpha = 0.8, size = .05) +
  scale_fill_staples(discrete = T, palette = 'new') +
  theme(
    axis.ticks = element_line(color = NA),
    axis.line = element_line(color = NA),
    axis.text = element_text(color = NA),
    legend.title = element_text(face = 'bold', size = 12)) +
  guides(fill=guide_legend(title="Farms per 10,000"),
         color=guide_legend(title="Farms per 10,000")) +
  labs(title = 'Farms per capita are highest in the Midwest and the South',
       subtitle = 'The states most susceptible to agricultural export tariffs are spread across the middle of the nation, \nparticularly the Dakotas. These areas will continue to struggle as the traade war intensifies.',
       caption = 'Data Source: Iowa Community Indicators Program')

The broader picture

When it comes to the US-China trade war, this analysis finds a variety of populations that have already or will soon be acutely impacted by exacerbated tariff regimes. In particular, large urban areas in California, Texas, and other large states will suffer from increasing costs to consumer goods, including electronics and other machinery. Meanwhile, the Midwest and South’s rural communities will be most impacted by agricultural tariffs and effective embargoes.

Together, these reinforce a more nuanced perspective; that the true victims of the trade war are not found at a national level. Instead, they are found in the rural communities relying on agricultural exports. They are found in the low-income areas of urbanized states, where goods made affordable by Chinese imports may soon be out of grasp again. They are found in the industries relying on the Chinese market access for growth. It is these communities, individuals, and firms who will bear the cost of this trade war, and as such effective policy should look to these bellweather actors to see what an exacerbated conflict may bring.

Additionally, all of this being said, it is vital to note that China is only one of the players impacting the U.S.-World deficit. Deficits with a variety of other nations account for the greatest share of our total national deficit to the World. Further, we rely on China for a fifth of our total imports, meaning with planned tariffs it will be difficult for other major trade partners Mexico and Canada to pick up the slack. How these trade relations will rebalance is uncertain.

# Source: https://www.census.gov/foreign-trade/balance/index.html
# Use only 2017 numbers, make base unit 10s of billions
waf <- USuni[USuni$year == 2017,] %>%
        ddply(.(cty_name), summarize,
          imports = sum(imports)/10000,
          exports = sum(exports)/10000)

# Get top 5 trade partners for manual input
waf_imp <- waf[order(-waf$imports),][1:5,]
waf_exp <- waf[order(-waf$exports),][1:5,]

imp <- c(`China` = 50,
         `Mexico` = 31,
         `Canada` = 30,
         `Japan` = 14,
         `Germany` = 12,
         `All Others` = 97)

exp <- c(`China` = 13,
         `Mexico` = 24,
         `Canada` = 28,
         `Japan` = 7,
         `Germany` = 5,
         `All Others` = 77,
         80)

library(waffle)

par(family = "Saira Condensed")
iron(
  waffle(exp, rows = 8, size = 1,
         colors = c("#CC0032", "#FF5A4C", "#00FFB5", "#149DCC", "#317E99", 'grey70', 'white'),
         title = '2017 US Exports to the World',
         xlab = '1 square = $10 billion in trade'),
  waffle(imp, rows = 8, size = 1,
         colors = c("#CC0032", "#FF5A4C", "#00FFB5", "#149DCC", "#317E99", 'grey70'),
         title = '2017 US Imports from the World',
         xlab = 'Data Source: United States Census Bureau')
  )